/**
 * axios拦截器
 */
import axios from 'axios'
import router from '../router/router'
import store from '../store/index'
import view from './view'
import {getSign} from "./sign"

// 超时时间
axios.defaults.timeout = 10000;
// http request 请求拦截器，有token值则配置上token值
axios.interceptors.request.use(
    config => {
        let timestamp = new Date().getTime();
        let sign = getSign(config.data, timestamp);
        config.headers['Sign'] = sign;
        config.headers['SendTime'] = timestamp;
        let token = store.state.token.token;
        if (token) {  // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
            config.headers['Token'] = token;
            return config;
        } else {
            //如果没有token 直接跳到登录页面
            view.showMsg("检测当您当前没有登录！", "error");
            router.replace({
                path: '/login',
                query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
            })
        }

    },
    err => {
        view.showMsg("当前发出的网络请求出现了致命的错误");
        return Promise.reject(err);
    });

// http response 服务器响应拦截器，这里拦截401错误，并重新跳入登页重新获取token
axios.interceptors.response.use(
    response => {
        switch (response.data.code) {
            case 40001:
                view.showMsg("error", "您当前的登录状态已经过期,请重新登陆！");
                store.commit('CLEAR_TOKEN');
                router.replace({
                    path: '/login',
                    query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                });
                break;
            default:
                return response;
        }

    },
    error => {
        view.showMsg( "服务器的返回值出现错误！请检查","error");
        return Promise.reject(error.response)
    });

